package com.gaohe.controller;

import com.alibaba.fastjson.JSON;
import com.gaohe.pojo.Goods;
import com.gaohe.pojo.User;
import com.gaohe.service.GoodsService;
import com.gaohe.service.UserService;
import com.gaohe.untils.CheckCodeUtil;
import com.gaohe.vo.InputVo;
import com.gaohe.vo.LoginVo;
import com.gaohe.vo.RegisterVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    public void login(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        LoginVo loginVo = JSON.parseObject(s, LoginVo.class);
//        System.out.println(loginVo.getUsername());
        UserService userService = new UserService();
        User user = userService.findByUsername(loginVo.getUsername());
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if (user == null){
            writer.write("nouser");
            return;//跳出if语句，不再执行下面语句
        } else {//用户存在
            if (user.getPassword().equals(loginVo.getPassword())){//密码正确
                session.setAttribute("user",user);//将根据字段查到的user传给服务器的session中
                if (loginVo.getState() == true){//记住密码
                    addCookie(resp, user,60*60*24*7);//以秒为单位
                }else {
                    addCookie(resp, user,0);
                }
                writer.write("succeed");
                return;
            }else {
                writer.write("failed");
                return;
            }
        }
    }
    public void register(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        RegisterVo registerVo = JSON.parseObject(s, RegisterVo.class);
        String code = registerVo.getCode();
        HttpSession session = req.getSession();
        String codeSession = (String) session.getAttribute("code");
        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        UserService userService = new UserService();
        if (code.equalsIgnoreCase(codeSession)){//忽略大小写的比较
//        userService.findByUsername()
            User user = new User();
            user.setUsername(registerVo.getUsername());
            user.setName(registerVo.getName());
            user.setPassword(registerVo.getPassword());
            int i = userService.add(user);

            if (i == 0){
                writer.write("failed");//用户已存在
            }else {
                writer.write("succeed");
            }
        }else {
            writer.write("codefal");//验证码输入错误
        }
    }
    public void code(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        ServletOutputStream os = resp.getOutputStream();
        String s = CheckCodeUtil.outputVerifyImage(200, 40, os, 4);
        session.setAttribute("code",s);//把code写进session中，后续比较
        System.out.println(s);//验证码的4个字符
    }
    private void addCookie(HttpServletResponse resp, User user, int i) {
//        Cookie username = new Cookie("username", user.getUsername());
        Cookie username = new Cookie("username", URLEncoder.encode(user.getUsername()));
        Cookie password = new Cookie("password", user.getPassword());
        username.setMaxAge(i);
        password.setMaxAge(i);
        resp.addCookie(username);
        resp.addCookie(password);
    }
    public void getName(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        String jsonString = JSON.toJSONString(user);
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write(jsonString);
    }
    public void logout(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        resp.getWriter().write("1");//写任意内容均可，因为前端函数中不需要resp传的data
    }
    public void buy(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String price = req.getParameter("price");
//        System.out.println(price);
        String username = req.getParameter("username");
        UserService userService = new UserService();
//        通过username获取的user
        User user = userService.findByUsername(username);
        PrintWriter writer = resp.getWriter();
//        判断user中的money是否足够买该物品
        if (user.getMoney() >= Double.parseDouble(price)){
            int buy = userService.buy(Double.parseDouble(price), username);
            if (buy == 0){
                writer.write("failed");//网络问题
            }else {
                writer.write("succeed");
            }
        }else {
            writer.write("notenough");
        }
    }
    public void getSession(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        PrintWriter writer = resp.getWriter();
        if (user == null){
            writer.write("none");
        }else {
            writer.write("succeed");
        }
    }
}
